var $ = exports

var objectUtils = require("objectUtils")

var def = function(name, fun) {
	objectUtils.def(Array.prototype, name, fun)
}

def("flatten", function() {
	var rv = []
	for( var i=0; i<this.length; i++) {
		var e = this[i]
		if (e.constructor === Array) {
			rv = rv.concat( e.flatten() )
			
		} else {
			rv.push(e)
		}
	}
	return rv
})

def("any", function(cond0) {
	var cond = (typeof cond0 == "function") ? cond0 : function(e) {
		return e === cond0
	}
	var i = 0 
	while( !cond(this[i]) && i < this.length ) {
		i += 1
	}
	return !(i === this.length)
})

def("reduce", function(f, initial) {
	var r = initial
	this.forEach(function(e) {
		r = f(r, e)
	})
	return r
})

def("forEach", function(f) {
	for( var i=0; i<this.length; i++ ) {
		f(this[i],i)
	}
})

def("map", function(f) {
	var rv = []
  var that = this
	this.forEach(function(elem,i) { rv[i] = f(that[i])})
	return rv
})

$.fromArguments = function(args, startIndex) {
	var rv = []
	startIndex = startIndex || 0
	for ( var i = startIndex; i < args.length; i++) {
		rv[i - startIndex] = args[i];
	}
	return rv
}

$.isArray = function(o) {
	return typeof o === "object" && o.constructor === Array
}

if (require.env === "rhino") {
	def("toJavaArray", function(type) {
		type = type || java.lang.Object
		
		var jArray = java.lang.reflect.Array.newInstance(type, this.length)
		this.forEach(function(v,i) { jArray[i] = v })
		return jArray
	})
	
	$.fromIterator = function(it) {
		var rv = []
		while(it.hasNext()) {
			rv.push(it.next())
		}
		return rv
	}
}

